<?php
/**
 * Created by PhpStorm.
 * User: DR
 * Date: 2018/8/2
 * Time: 17:18
 */

namespace app\api\controller;


use app\api\model\Order;
use app\common\controller\Api;
use app\api\model\UserMill;
use app\api\model\User;
use fast\Http;
use app\api\model\Deal;
use app\common\model\UserCert;
use think\Db;

/*
 * 用户中心接口
 */

class Usercenter extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    protected $failException = true;

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
    }

    /*
     * 用户中心首页
     *
     * @param string $token 用户token
     *
     */

    public function index()
    {
        $user = $this->auth->getUser();
        if(!$user->cny_address){
            db('user')->where(['id'=>$user->id])->update(['cny_address'=>md5($user->id)]);
        }
        // dump($user);die;
        $user = db('user')->where(['id'=>$user->id])->find();
        $data = [
            'avatar' => $user['avatar'],
            'nickname' => $user['nickname'],
            'username' => $user['username'],
            'cny_address' => $user['cny_address'],
            'id' => $user['id'],

        ];
        $this->success('success', $data);
    }

    /*
     * 卖家信息
     */
    public function sellerInfo()
    {
        $data = $this->request->request();
        $rule = [
          'user_id' => 'require|integer'
        ];
        $this->validate($data,$rule);
        $userCertModel = new UserCert();
        $userModel = new \app\common\model\User();
        $userinfo = $userModel->where(['id'=>$data['user_id']])->find();
        $user = $userCertModel
            ->where(['user_id'=>$data['user_id']])
            ->field('wechat,alipay,bank_address,bank_card,bank_realname')
            ->find();
        $user['phone'] = $userinfo->mobile;
        if(!$user){
            $this->error('用户不存在');
        }
        $this->success('success',$user);
    }



    /*
     * 取消订单
     * @param string $deal_sn 交易号
     */
    public function cancelDeal()
    {
        $data = $this->request->request();
        $rule = [
            'deal_sn' => 'require',
        ];
        $this->validate($data, $rule);
        $user = $this->auth->getUser();
        $where = [
            'deal_sn' => $data['deal_sn'],
            'user_id' => $user->id,
            'status' => 1
        ];
        $deal = Deal::get($where);
        if(!$deal)
        {
            $this->error('订单不存在或不能取消');
        }
        $deal->status = 0;
        $deal->residue_cny = 0;
        $deal->save();
        if($deal->type == 1){
            $cny = $deal->cny;
            $user->freeze_cny -= $cny*(1+config('site.fee'));
            $user->cny += $cny*(1+config('site.fee'));
            $user->save();
            account_log($user->id,$cny*(1+config('site.fee')),$user->cny+$user->freeze_cny,'',$user->sac,'撤销订单号:'.$deal->deal_sn,$cny*-1,$deal->deal_sn);
        }

        $this->success('订单撤销成功!');
    }

    /*
     * 确定付款订单状态
     * @param string $buy_deal_sn 买单号
     * @param string $sale_deal_sn 卖单号
     * @param string $order_sn 订单号
//     * @param int $status 1=确认付款,2=确认收款
     */
    public function payStatus()
    {
        $data = $this->request->request();
        $rule = [
            'order_sn' => 'require',
        ];
        $this->validate($data, $rule);
        $data['buy_remark'] = $this->request->request('buy_remark') ? $this->request->request('buy_remark') : '';
        if (strlen($data['buy_remark']) > 100)
        {
            $this->error('留言超出长度限制');
        }
        $user= $this->auth->getUser();
      	$pay_password = $this->auth->getEncryptPassword($data['pay_password'],$user->salt);
        if($user->pay_password != $pay_password)
        {
            $this->error('支付密码不正确');
        }
        $result = Deal::payStatus($data['order_sn'],$user,$data['buy_remark']);
        if($result)
        {

            $sold_user_info = db('order')
                ->alias('o')->field('u.mobile,o.sale_deal_sn')
                ->join('user u','u.id = o.sale_user_id')
                ->where('o.order_sn','=',$data['order_sn'])->find();
            if ($sold_user_info)
            {
                send_matched_sms($sold_user_info['mobile'],$data['order_sn'],'确认付款');
            }
            $this->success('付款成功!等待付币!');
        }else{
            $this->error('error');
        }
    }
    //确认订单
//    public function confirmStatus()
//    {
//        $data = $this->request->request();
//        $rule = [
//            'deal_sn' => 'require',
//        ];
//        $this->validate($data, $rule);
//        $result = Deal::confirmStatus($data['order_sn']);
//        if($result)
//        {
//            $this->success('success');
//        }else{
//            $this->error('error');
//        }
//    }


    /*
     * 我的团队
     */
    public function myTeam()
    {
        $page = $this->request->request('page');
        $listRows = $this->request->request('listRows');
        $user = $this->auth->getUser();
        $myTeam = User::getMyTeam($user->id, $listRows, $page);
        $myTeamCount = User::getMyTeamCount($user->id);
        $myreferees = User::get(
            ['id' => $user->first]
        );
        $me['avatar'] = $user->avatar;
        $me['nickname'] = $user->nickname;
        $me['id'] = $user->id;
        $realname = Db::name('user_certification')->where('user_id','=',$user->id)->find()['bank_realname'];
        $me['name'] = $realname;
        $data = [
            'myreferees' => $myreferees,
            'me' => $me,
            'myteam' => $myTeam,
            'teamcount' => $myTeamCount,
        ];
        $this->success('success', $data);
    }

    /*
     * 我的矿机
     * @param string $token 用户token
     */
    public function myMills()
    {
        $user = $this->auth->getUser();
        //计算我的算力
        $force = 0;
        $where['status'] = 1;
        $where['user_id'] = $user->id;
        $mymill = db('user_mill')->where($where)->select();
        if($mymill){
            foreach($mymill as $k=>$v){
                //查矿机信息
                $mill = db('mill')->where(['id'=>$v['mill_id']])->find();
                //算力
                $force+=($mill['price']/100);
                
            }
        }
        $mymills = db('user_mill')->where(['user_id'=>$user->id])->order('status ASC')->select();
        // $usermill = new UserMill();
        // $mymills = $usermill
        //     ->with('mill')
        //     ->where('user_id', $user->id)
        //     ->order('status ASC')
        //     ->select();
        foreach($mymills as $k=>$v){
            $mill = db('mill')->where(['id'=>$v['mill_id']])->find();
            if($v['status']==2){
                $mill['mill_name'] = '过期'.$mill['mill_name'];
            }
            $mymills[$k]['mill'] = $mill;
            $mymills[$k]['buy_time'] = date('Y-m-d H:i:s',$v['buy_time']);
            $mymills[$k]['start_time'] = date('Y-m-d H:i:s',$v['start_time']);
            $mymills[$k]['end_time'] = date('Y-m-d H:i:s',$v['end_time']);
            $mymills[$k]['last_time'] = date('Y-m-d H:i:s',$v['last_time']);
            $mymills[$k]['period'] = round(($v['end_time'] - $v['last_time'])/(24*60*60),1);
            //已经产币
            $mymills[$k]['coin_num'] = db('user_account_log')->where(['user_mill'=>$v['id'],'user_id'=>$v['user_id']])->sum('sac');
            //昨日产币
            $mymills[$k]['z_coin_num'] = db('user_account_log')->where(['user_mill'=>$v['id'],'user_id'=>$v['user_id']])->whereTime('change_time','yesterday')->sum('sac');
            
        }
        
        $data['mymills'] = $mymills;
        $data['force'] = $force;
        $this->success('success', $data);
    }

    /*
     * 启动矿机
     * @param string $token 用户token
     * @param int $usermill_id 当前用户购买矿机id
     */
    public function startMyMill()
    {
        $data = $this->request->request();
        $rule = [
            'usermill_id' => 'require|integer'
        ];
        $this->validate($data, $rule);
        $user = $this->auth->getUser();
        UserMill::startMyMill($data['usermill_id'], $user->id);
        $this->success('启动成功!');
    }

    /*
     * 获取sac单价
     * @param string $token 用户token
     */
    public function sacPriceAndNum()
    {
        $data = Http::get(config('sac_url'));
        $data = json_decode($data, true);
        $price = end($data['price_usd'])[1];        //比特币
        $rate = config('site.rate');
        $sacprice = config('site.localprice');
        $user = $this->auth->getUser();
        $data = [
            'sacprice' => round($sacprice, 2),
            'sacnum' => round($user->sac,4),
        ];
        if ($sacprice) {
            $this->success('success', $data);
        } else {
            $this->error('error');
        }
    }

    /*
     * 兑换CNY
     * @param string $token 用户token
     * @param float $sacprice sac价格
     * @param float $sacnum 出售sac的数量
     * @param string
     */
    public function exchangeSac()
    {
        $data = $this->request->request();
        $rule = [
            'sacprice' => 'require|float',
            'sacnum' => 'require|float|gt:0',
            'pay_password' => 'require',
        ];
        $this->validate($data, $rule);
        $user = $this->auth->getUser();
        $pay_password = $this->auth->getEncryptPassword($data['pay_password'], $user->salt);
        if ($user->pay_password != $pay_password) {
            $this->error('支付密码不正确');
        }
        if (round($user->sac,4) < $data['sacnum']) {
            $this->error('sac数量不足');
        }
        $datas = Http::get(config('sac_url'));
        $datas = json_decode($datas, true);
        $price = end($datas['price_usd'])[1];        //比特币
        $rate = config('site.rate');
        $sacprice = config('site.localprice');
        if ($data['sacprice'] > $sacprice) {
            $this->error('SAC价格高于现价', ['sacprice' => $sacprice]);
        }
        User::exchangeSac($user, $data);
        $this->success('兑换成功!');
    }

    /*
     * 获取CNY
     * @param string $token 用户token
     */
    public function haveCny()
    {
        $user = $this->auth->getUser();
        $data = [
            'canuse_cny' => $user->cny,
            'freeze_cny' => $user->freeze_cny,
        ];
        $this->success('success', $data);
    }
}